<template>
    <div style="background-color: #fff; height: 100%;overflow-x:auto;">
        <div style="display: flex; justify-content: space-between;">
            <a-form ref="formRef" size="small" :model="pageData" layout="inline" style="margin-top: 20px;">
                <a-form-item label="工段">
                    <a-select style="width: 200px" class="bacClass" @search="sectionSearch()" @change="processSearch()"
                        v-model="pageData.sectionName" allow-search allow-clear>
                        <a-option v-for="item in pageData.sectionNameList" :value="item.sectionName" :key="item">
                            {{ item.sectionName }}
                        </a-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="工序">
                    <a-select style="width: 200px" class="bacClass" @search="processSearch()"
                        v-model="pageData.processId" allow-search allow-clear>
                        <a-option v-for="item in pageData.processList" :value="item.id" :key="item">
                            {{ item.processName }}
                        </a-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="流转卡号" field="flowCardCode" :validate-trigger="['change', 'blur']"
                    :rules="[{ required: true, message: '流转卡号必填' }]">
                    <a-input class="bacClass" style="width: 200px" v-model="pageData.flowCardCode"
                        allow-clear></a-input>
                </a-form-item>
            </a-form>
            <Toolbar style="margin-top: 20px;" :items="['查询']" @select="selectHandle"> </Toolbar>
        </div>
        <div class="cssTable">
            <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height: 100%; width: 100%; z-index: 999">
                <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                    style="height: 74vh;" :suppressDragLeaveHidesColumns="true" rowSelection="multiple"
                    @grid-ready="gridReady" :defaultColDef="defaultColDef" class="ag-theme-alpine"
                    :rowData="pageData.tableList" :columnDefs="tableColumns" :localeText="localeText1">
                </AgGridVuesCopys>
            </a-spin>
        </div>
        <paginationCopys :page-size-options="pagingList1" :total="total" show-total show-jumper show-page-size
            @change="PageSize" @page-size-change="change1" style="justify-content: center; margin-top: 12px"
            :page-size="size" :current="page" />
    </div>
    <a-drawer style="z-index: 999" ok-text="保存" cancel-text="关闭" :drawer-style="{ zIndex: 9999 }" :mask-closable="false"
        :visible="pageData.showAdd" unmountOnClose placement="bottom" height="100%" @ok="sideOk"
        @cancel="pageData.showAdd = false">
        <template #title>{{ pageData.sideTitle }}</template>
        <template #footer>
            <a-button @click="pageData.showAdd = false">关闭</a-button>
            <a-button v-if="pageData.sideTitle != '异常描述'" type="primary" @click="sideOk">保存</a-button>
        </template>
        <div>
            <el-button :icon="EditPen" @click="pageData.sideTitle = '修改'" v-if="pageData.sideTitle === '异常描述'">修改</el-button>
            <el-button :icon="CirclePlus" @click="addRow()" type="success"
            v-if="pageData.sideTitle != '异常描述'">新增行</el-button>
            <el-button :icon="Delete" @click="delRow()" v-if="pageData.sideTitle != '异常描述'">删除</el-button>
            <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                style="height: 76vh;margin-top: 10px;" :suppressDragLeaveHidesColumns="true" rowSelection="multiple"
                @grid-ready="gridReadyDJ" :defaultColDef="defaultColDef" class="ag-theme-alpine"
                :rowData="pageData.checkList" :columnDefs="tableColumnsDJ" :localeText="localeText1">
            </AgGridVuesCopys>
        </div>
    </a-drawer>

</template>

<script lang='ts' setup>
import { reactive, toRefs, ref, onMounted } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { post, get } from '@/api/http'
import { Message, Modal } from '@arco-design/web-vue'

import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
import { Search, CirclePlus, Delete, EditPen } from "@element-plus/icons-vue";

const pagingList1: any = ref(pagingList)
const localeText1: any = ref(localeText)
const pageData: any = reactive({
    showAdd: false,
    sideTitle: '',
    rHeight: 0,
    tableList: [],
    checkList: [],
    pageLoading: false,
    flowCardCode: '',
    sectionName:'',
    processId:null,
    processList:[],
    sectionNameList:[],
})

const dataForm: any = reactive({
    flowCardCode: '',
    processId: null,
    processName: '',
    handlerList: [],
    isEdit: false,
    companyId: null,
    applyEmployee: '',
    applyDept: '',
})

const defaultColDef: any = {
    sortable: true,
    resizable: true,
    filter: true,
    flex: 1,
}

const gridOption = ref()
const gridReady = (params: any) => {
    gridOption.value = params.api
}

const tableColumns: any = [
    {
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
    },
    { headerName: '流转卡号', field: 'flowCardCode', width: 250 },
    { headerName: '工段', field: 'sectionName', width: 250 },
    { headerName: '工序', field: 'processName', width: 250 },
    { headerName: '客户', field: 'customName', width: 250 },
    { headerName: '色号', field: 'colorCode', width: 250 },
    { headerName: '色称', field: 'colorName', width: 250 },
    { headerName: '布号', field: 'clothCode', width: 250 },
    { headerName: '匹数', field: 'houseNum', width: 250 },
    { headerName: '创建时间', field: 'createTime', width: 250 },
    {
        headerName: '操作',
        field: 'action',
        width: 146,
        pinned: 'right',
        cellRenderer: {
            template: `<el-button style="color:#165dff;" link @click="c">登记</el-button>`,
            setup(props: any) {
                const c = () => {
                    checkIn(props.params.data)
                }
                return {
                    c,
                }
            },
        },
    },
]

const gridOptionDJ = ref()
const gridReadyDJ = (params: any) => {
    gridOptionDJ.value = params.api
}

const tableColumnsDJ: any = [
    {
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
    },
    {
        headerName: '问题类型', field: 'exceptionType',
        cellRenderer: {
            template: ` <span v-if="pageData.sideTitle === '异常描述'">{{val.exceptionType}}</span>
                        <a-input v-else class="bacClass" v-model="val.exceptionType"></a-input>`,
            setup(props: any) {
                const val = ref(props.params.data);
                return {
                    val,
                    pageData,
                };
            },
        },
    },
    {
        headerName: '问题描述', field: 'exceptionDesc',
        cellRenderer: {
            template: ` <span v-if="pageData.sideTitle === '异常描述'">{{val.exceptionDesc}}</span>
                        <a-input v-else class="bacClass" v-model="val.exceptionDesc"></a-input>`,
            setup(props: any) {
                const val = ref(props.params.data);
                return {
                    val,
                    pageData,
                };
            },
        },
    },
    {
        headerName: '不合格数量', field: 'unqualifiedNum',
        cellRenderer: {
            template: ` <span v-if="pageData.sideTitle === '异常描述'">{{val.unqualifiedNum}}</span>
                        <a-input-number v-else class="bacClass" v-model="val.unqualifiedNum" :min="0" />`,
            setup(props: any) {
                const val = ref(props.params.data);
                return {
                    val,
                    pageData,
                };
            },
        },
    },
    {
        headerName: '需求跟进单位', field: 'handlerEmployeeCode',
        cellRenderer: {
            template: ` <span v-if="pageData.sideTitle === '异常描述'">{{val.handleDept+'/'+val.handler}}</span>
                    <el-select v-else v-model="val.handlerEmployeeCode" filterable clearable placeholder=" "
                        :collapse-tags-tooltip="true" class="bacClass" @change="handlerChange(val)" style="width:100%">
                        <el-option v-for="item in dataForm.handlerList" :key="item.code"
                            :label="item.departmentName + '/' + item.name" :value="item.code" />
                    </el-select>`,
            setup(props: any) {
                const val = ref(props.params.data);
                return {
                    val,
                    dataForm,
                    pageData,
                    handlerChange,
                };
            },
        },
    },
    {
        headerName: '备注', field: 'remark', width: 250,
        cellRenderer: {
            template: ` <span v-if="pageData.sideTitle === '异常描述'">{{val.remark}}</span>
                        <a-input v-else class="bacClass" v-model="val.remark"></a-input>`,
            setup(props: any) {
                const val = ref(props.params.data);
                return {
                    val,
                    pageData,
                };
            },
        },
    },
]

//分页
const total = ref(0)
const page = ref(1)
const size = ref(10)
function PageSize(val: any) {
    page.value = val
    doRefresh()
}
function change1(val: any) {
    size.value = val
    doRefresh()
}

//查询
const formRef = ref()
const doRefresh = () => {
    formRef.value?.validate().then((err: any) => {
        if (!err) {
            pageData.pageLoading = true
            post({
                url: '/aps/dwDefect/findProcessInfoByCondition',
                data: {
                    flowCardCode: pageData.flowCardCode,
                    sectionName:pageData.sectionName,
                    processId:pageData.processId,
                    page: page.value,
                    size: size.value
                }
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {
                        pageData.tableList = data.records
                        gridOption.value.setRowData(data.records)
                        total.value = data.total
                    }
                })
                .catch(console.log)
                .finally(() => {
                    pageData.pageLoading = false
                })
        }
    })
}

const selectHandle = () => {
    page.value = 1
    doRefresh()
}

//新增行
let isTypeIds = 0
const addRow = () => {
    pageData.checkList.push({
        'exceptionType': '',
        'exceptionDesc': '',
        'unqualifiedNum': '',
        'handlerEmployeeCode': '',
        'isTypeIds': isTypeIds++
    })
    setTimeout(function () { gridOptionDJ.value.setRowData(pageData.checkList) }, 0)
}

//删除行
const delRow = () => {
    if (gridOptionDJ.value.getSelectedRows().length == 0) {
        Message.warning('请选择要删除的数据！')
        return
    }
    let deleteId = pageData.checkList.map((item: any) => item.isTypeIds);
    let deleteIds = gridOptionDJ.value.getSelectedRows().map((item: any) => item.isTypeIds);
    let list = deleteId.filter((ids: any) => deleteIds.includes(ids));
    pageData.checkList = pageData.checkList.filter((item: any) => !list.includes(item.isTypeIds));
}

//异常描述 登记
const checkIn = (record: any) => {
    pageData.pageLoading = true
    dataForm.flowCardCode = record.flowCardCode
    dataForm.processId = record.processId
    dataForm.processName = record.processName
    get({
        url: '/aps/dwDefect/findDefectListByProcess',
        data: {
            processId: record.processId,
            flowCardCode: record.flowCardCode,
        }
    }).then(({ data, code, message }: any) => {
        if (code === 200) {
            pageData.checkList = data
            pageData.checkList.length == 0 ? pageData.sideTitle = '新增' : pageData.sideTitle = '异常描述'
            pageData.checkList.forEach((item: any) => {
                item['isTypeIds'] = isTypeIds++
            })
            pageData.showAdd = true
            pageData.pageLoading = false
        } else {
            Message.error(message)
        }
    })
}

//员工下拉
const getHandler = (val: any) => {
    post({
        url: 'org/hrEmployee/getList',
        data: {
            deleteState: 0,
            obsoleteState: 0,
            company_id: dataForm.companyId,
            department_id: '',
            ygText: val,
        }
    }).then(({ data, code }: any) => {
        if (code === 200) {
            dataForm.handlerList = data
        } else {
            Message.error({
                content: '该部门无员工信息！',
                duration: 5000,
            })
        }
    })
}

const handlerChange = (val: any) => {
    dataForm.handleDept = ''
    if (val) {
        let data = dataForm.handlerList.find((o: any) => val.handlerEmployeeCode === o.code);
        val.handleDept = data.departmentName
        val.handleDeptId = data.departmentId
        val.handler = data.name
    }
}

//获取当前登录账号
const getUserToken = () => {
    post({
        url: 'admin/acl/user/findUserToken',
    }).then((res: any) => {
        if (res.code === 200) {
            dataForm.companyId = res.data.data.firmId
            dataForm.applyEmployee = res.data.data.empMap.name
            dataForm.applyDept = res.data.data.department
        }
    })
}

//工段下拉框
const sectionSearch = () => {
    post({
        url: '/pdm/worksection/getFieldValue',
        data: {
            sectionName: pageData.sectionName,
        },
    }).then(({ data, code }: any) => {
        if (code === 200) {
            pageData.sectionNameList = data
        } else {
            Message.error({
                content: '查询失败！',
                duration: 5000,
            })
        }
    })
}

//工序下拉框
const processSearch = () => {
    pageData.processId = ''
    pageData.processList = []
    if (pageData.sectionName) {
        post({
            url: 'pdm/worksectionWorkprocedure/selectPage',
            data: {
                deleteState: 0,
                size: 10000,
                page: 1,
                sectionName: pageData.sectionName,
            },
        }).then(({ data, code }: any) => {
            if (code === 200) {
                pageData.processList = data.list
            }
        })
    }
}

//保存
const sideOk = () => {
    if (pageData.checkList.length === 0) {
        Message.warning('至少登记一条异常问题！')
        return
    }
    if (pageData.checkList.find((o: any) => !o.exceptionType)) {
        Message.warning('问题类型必填！')
        return
    }
    if (pageData.checkList.find((o: any) => !o.exceptionDesc)) {
        Message.warning('问题描述必填！')
        return
    }
    if (pageData.checkList.find((o: any) => !o.unqualifiedNum)) {
        Message.warning('不合格数量必填！')
        return
    }
    if (pageData.checkList.find((o: any) => !o.handlerEmployeeCode)) {
        Message.warning('需求跟进单位必填！')
        return
    }
    pageData.pageLoading = true
    post({
        url: '/aps/dwDefect/insertOrUpdateDefectInfo',
        data: pageData.checkList.map((o: any) => {
            o.applyEmployee = dataForm.applyEmployee,
            o.applyDept = dataForm.applyDept
            return {
                flowCardCode: dataForm.flowCardCode,
                processId: dataForm.processId,
                processName: dataForm.processName,
                ...o
            }
        }),
    }).then(({ code, message }) => {
        if (code == 200) {
            Message.success('成功')
            pageData.showAdd = false
            pageData.pageLoading = false
            doRefresh()
        } else {
            Message.error(message)
        }
    })
}

onMounted(() => {
    pageData.rHeight = document.getElementsByClassName('main-section')[0]?.clientHeight
    //弹出层的高
    if (pageData.rHeight !== undefined) {
        pageData.rHeight = pageData.rHeight
    }
    doRefresh()
    getUserToken()
    getHandler('')
    sectionSearch()
})

</script>
<style lang='less' scoped>
.main-container {
    height: 100%;
}

:deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
}

:deep(.arco-table-td-content) {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
</style>